#include "client_function.h"
#include "tast_queue.h"
#include "cmd_tast.h"
#include "file_transmit.h"
#include "sha256.h"

void* client_tsm_function(void* arg){
    tast_queue* q = (tast_queue*)arg; 
    cmd_tast* t;
    while(1){
        t = (cmd_tast*)tast_queue_pop(q);
        printf("TYPE:%d",t->cmdType);
        if(t->cmdType == CMD_TYPE_DOWNLOAD){
            file_recv(t->peerfd,".");
            
            char filehash[32];
            recv(t->peerfd,filehash,32,0);
            rename(filehash,t->content);
            close(t->peerfd);
            free(t);
        }

        if(t->cmdType == CMD_TYPE_DOWNLOAD_BG){
            file_recv_backguand(t->peerfd,".");
            
            char filehash[32];
            recv(t->peerfd,filehash,32,0);
            rename(filehash,t->content);
            close(t->peerfd);
            free(t);
        }


        if(t->cmdType == CMD_TYPE_UPLOAD){
            char sha256[33];
            strcpy(sha256,sha256_create(t->content));
            int err = send(t->peerfd,sha256,33,0);
            if(err == -1){
                error(0,errno,"upload send");
            }
            int send_fd = t->peerfd;
        //--------------------------------
            recv(t->peerfd,(char*)t,sizeof(cmd_tast),0);
            if(t->peerfd == -10){
                printf("not need to send\n");
                close(send_fd);
                printf("network_disk>> ");
                fflush(stdout);

                continue;
            }
        //--------------------------------
        
            file_send(send_fd,".",t->content);

            close(send_fd);
            free(t);
        }
        continue;
    }
    return NULL;
}
